//
//  AppleIDLoginTool.m
//  EnyaMusic
//
//  Created by yang on 2022/3/7.
//  Copyright © 2022 Enya Technology. All rights reserved.
//

#import "AppleIDLoginTool.h"
#import <AuthenticationServices/AuthenticationServices.h>

@interface AppleIDLoginTool()<ASAuthorizationControllerDelegate,ASAuthorizationControllerPresentationContextProviding>
@property (nonatomic,copy)loginSuccessBlock successBlock;
@end

@implementation AppleIDLoginTool

+ (instancetype)shared {
    static AppleIDLoginTool *tool = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        tool = [[AppleIDLoginTool alloc]init];
    });
    return tool;
}




+ (void)loginWithAppleId:(loginSuccessBlock)block;
{
    if (@available(iOS 13.0, *)) {
        [AppleIDLoginTool shared].successBlock = block;
        //基于用户的Apple ID 授权用户，生成用户授权请求的一种机制
        ASAuthorizationAppleIDProvider *appleIdProvider = [[ASAuthorizationAppleIDProvider alloc] init];
        //创建新的Apple ID授权请求
        ASAuthorizationAppleIDRequest *request = appleIdProvider.createRequest;
        //在用户授权期间请求的联系信息
        request.requestedScopes = @[ASAuthorizationScopeEmail,ASAuthorizationScopeFullName];
        //由ASAuthorizationAppleIDProvider创建的授权请求，管理授权请求的控制器
        ASAuthorizationController *controller = [[ASAuthorizationController alloc] initWithAuthorizationRequests:@[request]];
        //设置授权控制器通知授权请求的成功与失败的代理
        controller.delegate = [AppleIDLoginTool shared];
        //提供展示上下文的代理，在这个上下文中，系统可以展示授权界面给用户
        controller.presentationContextProvider = [AppleIDLoginTool shared];
        [controller performRequests];
    }else{
        NSLog(@"system is lower");
    }
}


#pragma mark - appleId登录代理方法


//授权成功的方法
-(void)authorizationController:(ASAuthorizationController *)controller didCompleteWithAuthorization:(ASAuthorization *)authorization API_AVAILABLE(ios(13.0)){
    
        if([authorization.credential isKindOfClass:[ASAuthorizationAppleIDCredential class]]){
            ASAuthorizationAppleIDCredential *apple = authorization.credential;
            ///将返回得到的user 存储起来
            NSString *userIdentifier = apple.user;
//            NSPersonNameComponents *fullName = apple.fullName;
//            NSString *email = apple.email;
//            //用于后台像苹果服务器验证身份信息
            NSData *identityToken = apple.identityToken;

            
            NSString * token = [[NSMutableString alloc] initWithData:identityToken encoding:NSUTF8StringEncoding];

            
            self.successBlock(userIdentifier,token);
   
        }
//        else if ([authorization.credential isKindOfClass:[ASPasswordCredential class]]){
//            
//            //// Sign in using an existing iCloud Keychain credential.
//            ASPasswordCredential *pass = authorization.credential;
//            NSString *username = pass.user;
//            NSString *passw = pass.password;
//            
//            
//        }
    
}

//授权失败的方法
- (void)authorizationController:(ASAuthorizationController *)controller didCompleteWithError:(NSError *)error  NS_SWIFT_NAME(authorizationController(controller:didCompleteWithError:)){
    NSLog(@"错误信息  %@",error);
    NSString *errorMsg;
    switch (error.code) {
        case ASAuthorizationErrorCanceled:
            errorMsg = @"您取消了授权请求";
            break;
        case ASAuthorizationErrorFailed:
            errorMsg = @"授权请求失败";
            break;
        case ASAuthorizationErrorInvalidResponse:
            errorMsg = @"授权请求无响应";
            break;
        case ASAuthorizationErrorNotHandled:
            errorMsg = @"未能处理授权请求";
            break;
        case ASAuthorizationErrorUnknown:
            errorMsg = @"授权请求发生未知原因错误";
            break;
        default:
            break;
    }
  
    NSLog(@"errorMsg - %@",errorMsg);
}

- (nonnull ASPresentationAnchor)presentationAnchorForAuthorizationController:(nonnull ASAuthorizationController *)controller  API_AVAILABLE(ios(13.0)){
    return UIApplication.sharedApplication.keyWindow;
}

@end
